# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import base64
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA


def _encrpt(string, public_key):
    # print('public_key', public_key)
    rsakey = RSA.importKey(public_key)  # 读取公钥
    # print('rsakey', rsakey, type(rsakey))

    cipher = Cipher_pksc1_v1_5.new(rsakey)
    # 因为encryptor.encrypt方法其内部就实现了加密再次Base64加密的过程，所以这里实际是通过下面的1和2完成了JSEncrypt的加密方法
    encrypt_text = cipher.encrypt(string.encode())  # 1.对账号密码组成的字符串加密
    # print('encrypt_text', encrypt_text)

    cipher_text_tmp = base64.b64encode(encrypt_text)  # 2.对加密后的字符串base64加密
    # print('cipher_text_tmp', cipher_text_tmp)

    return cipher_text_tmp.decode()


def rsa_encrypt(public_key,  aes_text):
    key = '-----BEGIN PUBLIC KEY-----\n' + public_key + '\n-----END PUBLIC KEY-----'
    encrypt_res = _encrpt(aes_text, key)
    # print('encrypt_res', encrypt_res)

    return encrypt_res


if __name__ == '__main__':

    PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClj0t1b+O5Cq06d0yp4qZHM3OhNSmoaArC6qAhehT/DB23F/CCUSFrQCjADhOvCq+xu4JcNGQ1kpjhKVNb642QPlSDJ04QM/+3mKcu/WKLDZ+3zQYvNY41pcjTyxtUT9ixaBx8OQQfOp+qiAYYBtE9T6WRLCrl1YN0drpDvFylyQIDAQAB"

    message = '6270B399EE3AD467DDEEEC43EE6AFE156A44FCA594A1C849480F0A1B0FAFEB16'

    message = '6270B399EE3AD467DDEEEC43EE6AFE15979F17041C78936E951AE0E1D189729B08A47305D1DD7B1CD4E08913C582C943'

    print('PUBLIC_KEY', PUBLIC_KEY)

    print('message', message)

    rsa_ok = rsa_encrypt(PUBLIC_KEY, message, )

    print('rsa_ok', rsa_ok)
